// Cloudflare R2 Worker for Words Discoverer Sync
// Deploy this worker to Cloudflare Workers and configure your R2 bucket

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    const path = url.pathname;
    const method = request.method;

    // CORS headers
    const corsHeaders = {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    };

    // Handle CORS preflight
    if (method === 'OPTIONS') {
      return new Response(null, { headers: corsHeaders });
    }

    // Authenticate requests
    const authHeader = request.headers.get('Authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return new Response(JSON.stringify({ success: false, error: 'Missing or invalid authorization header' }), {
        status: 401,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }

    const token = authHeader.slice(7);
    if (token !== env.API_TOKEN) {
      return new Response(JSON.stringify({ success: false, error: 'Invalid API token' }), {
        status: 401,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }

    try {
      if (path === '/upload' && method === 'PUT') {
        // Upload file to R2
        const body = await request.json();
        const { key, content } = body;
        
        if (!key || content === undefined) {
          return new Response(JSON.stringify({ success: false, error: 'Missing key or content' }), {
            status: 400,
            headers: { ...corsHeaders, 'Content-Type': 'application/json' }
          });
        }

        await env.R2_BUCKET.put(key, content, {
          httpMetadata: {
            contentType: 'text/plain',
          },
        });

        return new Response(JSON.stringify({ success: true }), {
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });

      } else if (path === '/download' && method === 'GET') {
        // Download file from R2
        const key = url.searchParams.get('key');
        
        if (!key) {
          return new Response(JSON.stringify({ success: false, error: 'Missing key parameter' }), {
            status: 400,
            headers: { ...corsHeaders, 'Content-Type': 'application/json' }
          });
        }

        const object = await env.R2_BUCKET.get(key);
        
        if (!object) {
          return new Response(JSON.stringify({ success: false, error: 'File not found' }), {
            status: 404,
            headers: { ...corsHeaders, 'Content-Type': 'application/json' }
          });
        }

        const content = await object.text();
        return new Response(content, {
          headers: { ...corsHeaders, 'Content-Type': 'text/plain' }
        });

      } else if (path === '/list' && method === 'GET') {
        // List files in R2 bucket
        const prefix = url.searchParams.get('prefix') || '';
        
        const objects = await env.R2_BUCKET.list({
          prefix: prefix,
          limit: 1000,
        });

        const files = objects.objects.map(obj => ({
          key: obj.key,
          size: obj.size,
          lastModified: obj.uploaded.toISOString(),
        }));

        return new Response(JSON.stringify({ success: true, files }), {
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });

      } else {
        return new Response(JSON.stringify({ success: false, error: 'Not found' }), {
          status: 404,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }

    } catch (error) {
      console.error('Worker error:', error);
      return new Response(JSON.stringify({ success: false, error: error.message }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  },
};

/*
Deployment Instructions:

1. Create a Cloudflare R2 bucket:
   - Go to Cloudflare Dashboard > R2 Object Storage
   - Create a bucket named "words-discoverer-sync" (or any name you prefer)

2. Create a Cloudflare Worker:
   - Go to Cloudflare Dashboard > Workers & Pages
   - Create a new Worker
   - Replace the default code with this script

3. Configure Environment Variables:
   - In your Worker settings, add these environment variables:
     - API_TOKEN: A secure token you generate (e.g., a UUID)   ->   0a26f9a7-378a-417c-af28-8c8dbd25c18d
   
4. Bind R2 Bucket:
   - In your Worker Binds > Add binding > R2 Bucket Bindings
   - Add binding: Variable name = "R2_BUCKET", Bucket name = your bucket name

5. Deploy the Worker:
   - Save and deploy your Worker
   - Note the Worker URL (e.g., https://your-worker.your-subdomain.workers.dev)   https://words-discoverer-sync.dailyapp66.workers.dev

6. Configure Words Discoverer Extension:
   - Open the extension settings
   - Enter your Worker URL and API_TOKEN in the R2 Configuration section
   - Click "Save Configuration"
   - Click "Synchronize Now" to start syncing

Security Notes:
- Keep your API_TOKEN secure and don't share it
- Consider using Cloudflare Access for additional security
- The R2 bucket should be private (not public)
*/